﻿using System;
using System.Diagnostics;
using System.IO;
using CommandLine;
using ExcelAutomator.Configuration;
using log4net;
using log4net.Config;

namespace ExcelAutomator.Console
{
	class Program
	{
		public static void Main(string[] args)
		{	
			ConfigureLogging();

			var options = new CommandLineOptions();
			var parser = new CommandLineParser(new CommandLineParserSettings{CaseSensitive = false,HelpWriter = System.Console.Error});
			
			if(parser.ParseArguments(args, options))
			{
				if (IsExcelRunning())
				{
					return;
				}

				var configFile = new FileInfo(options.ConfigurationFile);

				if(!configFile.Exists)
				{
					Log.Error(string.Format("The specified config file '{0}' doesn't exist.", options.ConfigurationFile));
					Environment.Exit(1);
				}

				try
				{
					var cfg = ExcelAutomatorConfiguration.FromXml(configFile.FullName);
					cfg.Settings.OutputFolder = options.OutputFolder.IsNOE() ? cfg.Settings.OutputFolder : options.OutputFolder;
					cfg.Settings.Input = options.Input.IsNOE() ? cfg.Settings.Input : options.Input;
					cfg.Settings.SearchPattern = options.SearchPattern;
					cfg.Settings.ScanSubFolders = options.ScanSubFolders;
					var excelAutomationService = new ExcelAutomationService(cfg);
					
					excelAutomationService.ExecuteAutomation();
				}
				catch (Exception e)
				{
					Log.Error(e.Message + " " + e.InnerException.Message, e);
					Environment.Exit(-1);
				}
				finally
				{
					Environment.Exit(1);
				}
			}
			else
			{
				Environment.Exit(1);
			}
		}

		private static void ConfigureLogging()
		{
			XmlConfigurator.Configure();
		}

		#region IsExcelRunning

		private static bool IsExcelRunning()
		{
			foreach(var process in Process.GetProcesses())
			{
				if (process.ProcessName.Equals("Excel", StringComparison.OrdinalIgnoreCase))
				{
					Log.Error(string.Format("Excel is currently running. Close your Excel Application first and make sure that no Excel process is running in your task manager."));
					return true;
				}
			}
			return false;
		}

		#endregion

		

		#region Log

		private static ILog Log
		{
			get { return LogManager.GetLogger(typeof (Program)); }
		}

		#endregion

	}
}
